package socket2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Server {
    private List<PrintWriter> s = Collections.synchronizedList(new ArrayList<>());
    private ServerSocket serverSocket;
    public Server() {
        try {
            System.out.println("打开服务端.....");
            //使用serverSocket与客户端建立连接
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端以打开");
            start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        while (true) {
            try {
                System.out.println("等待客户端连接");
                //调用serverSocket内部的.accept()方法获取用户输入过来的数据
                Socket socket =serverSocket.accept();
                System.out.println("客户端以连接");
                MyThread m1 = new MyThread(socket);
                Thread t1 = new Thread(m1);
                t1.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new Server();
    }


class MyThread extends Thread{

    private String host;
    private Socket socket;
    public MyThread(Socket socket){this.socket = socket;}
    public void asd (String line){
        synchronized (s) {
            System.out.println(line);
            s.forEach(p->p.println(line));
//            for (PrintWriter p : s) {
//                System.out.println(line);
//                p.println(line);
//            }
        }
    }
    public void run() {
        PrintWriter pw = null;
        try {
            host = socket.getLocalAddress().getHostAddress();
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String a;
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            pw = new PrintWriter(bw,true);
            synchronized (s) {
                s.add(pw);
            }
            asd(host+"上线了，当前在线人数"+s.size());
            while((a = br.readLine()) != null) {
              asd(host+"说"+a);
            }
        } catch (IOException e) {

        }finally {
            synchronized (s) {
                s.remove(pw);
                asd(host+"下线了");
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    }
}